package top.somliy.websocket.config;

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.server.HandshakeInterceptor;
import top.somliy.websocket.config.properties.WebSocketProperties;
import top.somliy.websocket.handler.AbstractConnectWebSocketHandler;

import java.util.List;

/**
 * 类名： @ClassName SomliyWebsocketAutoConfiguration 自动配置类
 * 创建人：@author zhao dong
 * 类描述：@Description: 自动配置类
 * 创建时间: 2023/11/19 10:06
 */
@AutoConfiguration
@ConditionalOnProperty(prefix = "project.websocket", value = "enable", matchIfMissing = true)
@EnableConfigurationProperties(WebSocketProperties.class)
public class SomliyWebsocketAutoConfiguration {
    /**
     * 配置类
     *
     * @param handshakeInterceptors           拦截器
     * @param abstractConnectWebSocketHandler 处理器
     * @param webSocketProperties             配置文件
     * @return 配置类
     */
    @Bean
    @ConditionalOnMissingBean
    public WebSocketConfigurer webSocketConfigurer(List<HandshakeInterceptor> handshakeInterceptors,
                                                   AbstractConnectWebSocketHandler abstractConnectWebSocketHandler,
                                                   WebSocketProperties webSocketProperties) {
        String path = webSocketProperties.getPath();
        return registry -> {
//            if (registry instanceof ServletWebSocketHandlerRegistry) {
//                //替换UrlPathHelper
//                ((ServletWebSocketHandlerRegistry) registry).setUrlPathHelper(new PrefixUrlPathHelper(path));
//            }

            registry.addHandler(abstractConnectWebSocketHandler, path)
                    // 添加拦截器可实现用户链接前进行权限校验等操作
                    .addInterceptors(handshakeInterceptors.toArray(new HandshakeInterceptor[0]))
                    // 设置允许跨域访问
                    .setAllowedOrigins("*");
        };
    }
}
